import store from '@/store/index.js';
import {
	delRepeatJson
} from './util.js';

/**
 * 排除购物车在产品库不存在的产品
 * */
class ExcludeCartProduct {
	// 原来的产品库 , 现在的产品库
	constructor(originProductsMap, nowProductsMap) {
		this.originProductsMap = originProductsMap;
		this.productsMap = nowProductsMap;
		this.cartList = [...store.state.cartList];
		this.menuCoupons = {};
		this.noExistProductIds = []; // 不存在的产品id
	}

	// 排除不存在的产品
	excludeProduct() {
		const {
			cartList,
			originProductsMap,
			productsMap
		} = this;

		const noExistIds = []; // 不存在产品id

		// 筛选出不存在的产品（含售罄，basePrice不同的）和 加价购产品 & 不满足产品券使用条件的
		cartList.map(item => {
			if (item.isRelasionSale === '2') {
				noExistIds.push(item.productId);
			} else {
				if (!productsMap[item.productId]) {
					noExistIds.push(item.productId);
				} else {
					const oldPro = originProductsMap[item.productId] || '';
					const newPro = productsMap[item.productId] || '';
					if (newPro.displayOrder < 0 || oldPro.basePrice !== newPro.basePrice) {
						noExistIds.push(item.productId);
					}
				}
			}
		});

		if (noExistIds.length) {

			const noExistProducts = this.getNoExistProducts(noExistIds);
			store.commit('handleNoExistProducts', noExistProducts);

			// 去除 不存在的产品
			let newCartList = cartList.filter(x => {
				let flag = !(noExistIds.some(y => {
					return x.productId === y;
				}));
				return flag;
			});
			return newCartList;

		} else {
			return cartList;
		}

	}

	// 排除不可用产品券
	excludeCoupon(newCartList) {
		// 可使用的优惠券
		const usable = this.menuCoupons.usable || [];
		// 购物车存在的产品券产品
		const hasCouponProducts = newCartList.filter(item => item.couponId) || [];
		// 不存在的id列表
		let noExistIds = [];

		if (usable.length) {
			hasCouponProducts.map(x => {
				let flag = usable.some(y => {
					return x.couponId === y.id;
				});
				
				if (!flag) { // 这张券不可以使用
					noExistIds.push(x.productId)
				}
			})
			
		} else {
			hasCouponProducts.map(x => {
				noExistIds.push(x.productId)
			});
		}

		if (noExistIds.length) {
			// 去除 不存在产品券对应的产品
			newCartList = newCartList.filter(x => {
				let flag = !(noExistIds.some(y => {
					return x.productId === y && x.couponId;
				}));
				return flag;
			});
		}

		return newCartList;
	}

	// 获取不存在的产品列表
	getNoExistProducts(noExistIds) {
		const originProductsMap = this.originProductsMap;
		let list = [];
		noExistIds.map(item => {
			if (originProductsMap[item]) {
				list.push(originProductsMap[item])
			}
		});

		if (list.length) {
			list = delRepeatJson(list, 'id');
		}

		return list;
	}

	// 执行
	out() {
		const cartList = this.cartList;
		if (cartList.length) {
			let newCartList = this.excludeProduct();
			
			// if (newCartList.filter(x => x.couponId).length) {
			// 	newCartList = this.excludeCoupon(newCartList); // 排除不满足条件的产品券产品(暂不在此做判断)
			// }

			store.commit('handleCartList', newCartList);
		}

		uni.removeStorageSync('EEM'); // 移除标识
	}
}

module.exports = ExcludeCartProduct;
